﻿using System.Drawing;
using System.Media;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Entities;
using CloudShot.Forms;
using CloudShot.Interfaces;
using CloudShot.Logic;
using CloudShot.Properties;
using CloudShot.Utils;

namespace CloudShot.Capturers
{
  internal class ShotCapturer : ICapturer
  {
    protected readonly INotificationService NotificationService;
    protected readonly StorageContainer StorageContainer;
    protected readonly IConfigurationSection AppConfigurationSection;
    private readonly bool _isCaptureMouseCursor;
    private readonly bool _isSoundsEnabled;
    private readonly bool _isInstantShot;
    private readonly Color _fillColor;

    public ShotCapturer(StorageContainer storageContainer, IConfigurationSection appConfigurationSection, INotificationService notificationService,
                        bool isCaptureMouseCursor, bool isSoundsEnabled, Color fillColor, bool isInstantShot)
    {
      StorageContainer = storageContainer;
      AppConfigurationSection = appConfigurationSection;
      NotificationService = notificationService;
      _isCaptureMouseCursor = isCaptureMouseCursor;
      _isSoundsEnabled = isSoundsEnabled;
      _isInstantShot = isInstantShot;
      _fillColor = fillColor;
    }

    public Image Capture()
    {
      Rectangle screenSize = SystemInformation.VirtualScreen;
      Bitmap backgroundImage = ScreenCapture.CaptureRectangle(screenSize);

      if (_isCaptureMouseCursor)
      {
        var graphics = Graphics.FromImage(backgroundImage);
        graphics.DrawCurrentCursor(screenSize.Location);
      }

      //When you are shotting menus, sometimes focus stayed on menu. 
      //This call will close menu and set focus to current window.
      //SendKeys.SendWait("{Esc}");  //closes menu	

      using (var captureForm = new CaptureForm(StorageContainer, AppConfigurationSection, NotificationService, _fillColor, _isInstantShot, _isSoundsEnabled))
      {
        captureForm.StartPosition = FormStartPosition.Manual;
        captureForm.Location = screenSize.Location;
        captureForm.Size = screenSize.Size;
        captureForm.BackgroundImage = backgroundImage; //this code must be here, you must set beckground before form takes focus

        if (captureForm.ShowDialog() != DialogResult.OK)
          return null;

        CaptureResult result = captureForm.CaptureResult;

        captureForm.BackgroundImage = null;
        backgroundImage.Dispose();

        return GetImage(result);
      }
    }

    protected virtual Image GetImage(CaptureResult captureResult)
    {
      return captureResult.Image;
    }
  }
}